define([ './module' ], function(module) {
	'use strict';


	module.controller('basicregion',serverbasicregionctrl);
	function serverbasicregionctrl($state,$scope,$http,$location){
		$scope.gtparams=[];
		$scope.index=1;
		$scope.addgtparams=function(){
			var param={id:++$scope.index,name:'',sort:'1',status:'1',code:"a"};
			$scope.gtparams.push(param);
		}
		$scope.remove=function(index){
			$scope.gtparams.splice(index,1);
		}
		//通过location中的operate参数区分操作行为
		var operate=$location.search().operate;
		if(operate!=undefined&&operate=="save"){
			//控制保存按钮显示
			$scope.savebtn={show:true};
			$scope.title='添加区域';
			$scope.status="1";
			$scope.type="0";


			/**
			 *  查询所有省份
			 */
			$scope.findallshengfen=function(){
				$http({
					method:'POST',
					url:'../mall/basicregion/findRegionByType',
					data:{
						'type':"0"
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.shengfenall=data.beanlist;
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
						show:true,
						msg:'系统异常'
					}
				});
			}

			/**
			 *  查询省份下的市
			 */
			$scope.findallshibyshengfen=function(){
				$http({
					method:'POST',
					url:'../mall/basicregion/findRegionShiByShengfen',
					data:{
						'parentid':$scope.shengfenallx.id
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.shiall=data.beanlist;
						$scope.shishow=true;
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
						show:true,
						msg:'系统异常'
					}
				});
			}


			/**
			 * 省份选择改变
			 */
			$scope.changeshenfen=function(){
				if($scope.shengfenallx==undefined){
					$scope.errors={
						show:true,
						msg:"请选择省份"
					}
					return false;
				}
				$scope.findallshibyshengfen();
			}

			/**
			 * 区域改变
			 */
			$scope.$watch('type',function(){
				if($scope.type=="1"){
					//如果是市
					$scope.shengfenshow=true;
					$scope.shishow=false;
					$scope.qushow=false;
				}
				if($scope.type=="3"){
					//如果是区
					$scope.shengfenshow=true;
				}

			});

			//保存数据方法
			$scope.save=function(){

				if($scope.type=="0"){
					$scope.saveshengfen();
				}
				if($scope.type=="1"){
					$scope.saveshi();
				}
				if($scope.type=="3"){
					$scope.savequ();
				}

			};
			/**
			 * 保存省份
			 */
			$scope.saveshengfen=function(){
				$http({
					method:'POST',
					url:'../mall/basicregion/save',
					data:{
						'type':$scope.type,
						'status':$scope.status,
						'name':angular.toJson($scope.gtparams),
						'parentid':'',
						'parentname':'',
						'path':''
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.info={
							show:true,
							msg:'区域添加成功'
						}
						$location.path('/basicregionment');
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
						show:true,
						msg:'系统异常'
					}
				});
			};
			$scope.saveshi=function(){
				if($scope.shengfenallx==undefined){
					$scope.errors={
						show:true,
						msg:"请选择省份"
					}
					return false;
				}
				$http({
					method:'POST',
					url:'../mall/basicregion/save',
					data:{
						'type':$scope.type,
						'status':$scope.status,
						'name':angular.toJson($scope.gtparams),
						'parentid':$scope.shengfenallx.id,
						'parentname':$scope.shengfenallx.name,
						'path':$scope.shengfenallx.id
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.info={
							show:true,
							msg:'区域添加成功'
						}
						$location.path('/basicregionment');
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
						show:true,
						msg:'系统异常'
					}
				});
			};
			$scope.savequ=function(){
				if($scope.shiallx==undefined){
					$scope.errors={
						show:true,
						msg:"请选择市"
					}
					return false;
				}
				$http({
					method:'POST',
					url:'../mall/basicregion/save',
					data:{
						'type':$scope.type,
						'status':$scope.status,
						'name':angular.toJson($scope.gtparams),
						'parentid':$scope.shiallx.id,
						'parentname':$scope.shiallx.name,
						'path':$scope.shiallx.id
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.info={
							show:true,
							msg:'区域添加成功'
						}
						$location.path('/basicregionment');
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
						show:true,
						msg:'系统异常'
					}
				});
			}

		}

	}

	module.controller('basicregionment',serverbasicregionmentctrl);
	//查询列表数据
	function serverbasicregionmentctrl($http,$location,$compile,$scope,DTOptionsBuilder,DTColumnBuilder){
		$scope.title="区域列表";
		var vm=this;
		vm.message='';
		vm.someClickHandler = someClickHandler;
		vm.selected={};
		vm.selectAll=false;
		vm.toggleAll=toggleAll;
		vm.toggleOne=toggleOne;
		vm.dtInstance={};
		var titleHtml='<input type="checkbox" ng-model="showCase.selectAll" ng-click="showCase.toggleAll(showCase.selectAll,showCase.selected)">';
		vm.dtOptions=DTOptionsBuilder.newOptions().withOption('ajax',{
			type:'POST',
			url:'../mall/basicregion/findByPage',
			dataSrc:'data'
		})
		.withOption('processing',false)
		.withOption('paging',true)
		.withOption('serverSide',true)
		.withOption('createdRow',function(row,data,dataIndex){
			$compile(angular.element(row).contents())($scope);
		})
		.withOption('headerCallback', function(header) {
			if (!$scope.headerCompiled) {
          		$scope.headerCompiled = true;
          		$compile(angular.element(header).contents())($scope);
			}
    })
    .withOption('stateSave', true)
    .withOption('rowCallback',rowCallback)
		.withPaginationType('full_numbers')

		.withLanguageSource('./app/language/chinese.json');

		$scope.$on('handleRequest',function(){
		});
		vm.dtColumns=[
      DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function(data,type,full,meta){
    	  vm.selected[full.id]=false;
    	  return '<input type="checkbox" ng-model="showCase.selected['+data.id+']" ng-click="showCase.toggleOne(showCase.selected)">';
      }),
      DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
    	DTColumnBuilder.newColumn('name').withTitle('名称'),
			DTColumnBuilder.newColumn('parentname').withTitle('上级名称'),
			DTColumnBuilder.newColumn('type').withTitle('类型'),
			DTColumnBuilder.newColumn('status').withTitle('状态'),
    	DTColumnBuilder.newColumn('updatetime').withTitle('更新时间'),
    	DTColumnBuilder.newColumn('version').withTitle('版本号')
		];

		function reloadData(){
			var resetPaging = false;
	        vm.dtInstance.reloadData(callback, resetPaging);
		}
		function callback(data){
		}

		/**
		 * 复杂搜索刷新数据
		 */
		function searchReloadData(){
			var resetPaging=false;
			var searchParams={
				isCustomSearch:1,
				name:''
			};
			if($scope.name!=undefined){
				searchParams.name=$scope.name;
				vm.dtOptions['ajax'].data=searchParams;
				vm.dtInstance.reloadData(callback, resetPaging);
			}
		}

		/**
		 * 表格
		 */
		$scope.searchdataTableCustom=function(){
			searchReloadData();
		}

		//表格中编辑按钮
		$scope.edit=function(id){
			$location.path('/basicregion').search({'operate':'edit','id':id});
		}

		/**
		 * 跳转到添加商品类型和参数页面
		 */
		$scope.save=function(){

			$location.path('/basicregion').search({'operate':'save'});
		}

		/**
		 * 删除记录
		 */
		$scope.del=function(){
			var i=0;
			var ids=[];
			angular.forEach(vm.selected, function(data,index,array){
				if(data){
					i++;
					ids.push(index);
				}
			});
			if(i==0){
				$scope.errors={
						show:true,
						msg:'请选择一条记录'
				}
			}else{
				$scope.errors={
						show:false
				}
				//批量删除数据
				var idstrs=ids.join(",");
				$http({
					method:'POST',
					url:'../mall/basicregion/del',
					data:{
						'id':idstrs
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.info={
								show:true,
								msg:'删除成功'
						}
						reloadData();
					}

				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}
		}

		/**
		 * 列表全选
		 */
		function toggleAll(selectAll,selectedItems){
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					selectedItems[id]=selectAll;
				}
			}
		}
		/**
		 * 列表单选
		 */
		function toggleOne(selectedItems){
			var me=this;
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					if(!selectedItems[id]){
						me.selectAll=false;
					}
				}
			}
			me.selectAll=true;
		}

		function someClickHandler(info) {
	        vm.message = info.id + ' - ' + info.name;
	    }
		/**
		 * 单击列表某行回调
		 */
		function rowCallback(nRow,aData,iDisplayIndex,iDisplayIndexFull){
			$('td', nRow).unbind('click');
	        $('td', nRow).bind('click', function() {
	            $scope.$apply(function() {
	                vm.someClickHandler(aData);
	            });
	        });
	        return nRow;
		}

	}
});
